package com.hxz.graduationdesign.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.HashSet;
import java.util.Set;

public final class StopWordUtils {
    private static final StopWordUtils INSTANCE = new StopWordUtils();
    private final Set<String> stopWords;

    private StopWordUtils() {
        this.stopWords = loadStopWords("/text/stop-word.txt");
    }

    public static StopWordUtils getInstance() {
        return INSTANCE;
    }

    private Set<String> loadStopWords(String resourcePath) {
        Set<String> words = new HashSet<>();
        try (InputStream is = getClass().getResourceAsStream(resourcePath);
             BufferedReader reader = new BufferedReader(new InputStreamReader(is, StandardCharsets.UTF_8))) {
            String line;
            while ((line = reader.readLine()) != null) {
                line = line.trim();
                if (!line.isEmpty()) {
                    words.add(line);
                }
            }
        } catch (IOException | NullPointerException e) {
            throw new RuntimeException("Failed to load stop words: " + resourcePath, e);
        }
        return words;
    }

    public boolean isStopWord(String word) {
        return stopWords.contains(word);
    }

    public String filterStopWords(String text) {
        if (text == null || text.trim().isEmpty()) {
            return text;
        }

        StringBuilder result = new StringBuilder();
        // 简单分词（按空格和标点分割）
        String[] words = text.split("[\\s\\p{Punct}]+");

        for (String word : words) {
            if (!stopWords.contains(word)) {
                result.append(word).append(" ");
            }
        }

        return result.toString().trim();
    }
}